package com.lishe.lishe.lishe.module.myorder.fragment;

import android.app.Activity;
import android.os.Bundle;


import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.bean.SpaceItemDecoration;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.myorder.activity.LogisticsActivity;
import com.lishe.lishe.lishe.module.myorder.activity.OrderDetailsActivity;
import com.lishe.lishe.lishe.module.myorder.adapter.OrderAdapter;
import com.lishe.lishe.lishe.base.BaseFragment;
import com.lishe.lishe.lishe.module.myorder.adapter.OrderAdapter0;
import com.lishe.lishe.lishe.module.myorder.bean.BaseOrderDataBody;
import com.lishe.lishe.lishe.module.myorder.bean.OrderObject;
import com.lishe.lishe.lishe.module.myorder.presenter.OrderPresenter;
import com.lishe.lishe.lishe.module.pay.activity.PayActivity;
import com.lishe.lishe.lishe.pulltorefresh.PullToRefreshBase;
import com.lishe.lishe.lishe.pulltorefresh.PullToRefreshListView;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.lishe.widget.ConfirmDialog;
import com.lishe.lishe.lishe.widget.MessageDialog;
import com.lishe.lishe.retrofit.BaseRequestBody;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by law on 2017/8/11.
 * 订单模型
 */

public class MyOrdersModelFragment extends BaseFragment {
    private int ORDER_TYPE = 0;
    private RelativeLayout emptyLayout;
    private TextView tipText;
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;
    //    private OrderAdapter orderAdapter;
    private OrderAdapter0 orderAdapter0;
//    private LinkedList<OrderObject> lisOrders = new LinkedList<>();

    public static MyOrdersModelFragment newInstance(int type) {
        MyOrdersModelFragment fragment = new MyOrdersModelFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ORDER_TYPE = getArguments().getInt("type");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_my_orders_model, null);
        initView(v);
        v.setOnTouchListener(this);
        return v;
    }

    private void initView(View v) {
        emptyLayout = v.findViewById(R.id.emptyLayout);
        tipText = v.findViewById(R.id.tip_text);
//        orderAdapter = new OrderAdapter(getActivity(), orderObjects);
        orderAdapter0 = new OrderAdapter0(getActivity(), orderObjects);
//        listView = v.findViewById(R.id.listview);
//        listView.setAdapter(orderAdapter);
        recyclerView = v.findViewById(R.id.recyclerView);
        recyclerView.addItemDecoration(new SpaceItemDecoration(0,0,0, Utils.dip2px(getActivity(),15)));
        refreshLayout = v.findViewById(R.id.refreshlayout);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(orderAdapter0);
        recyclerView.setOnTouchListener(//避免更新数据是刷新闪退
                new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (refreshLayout.isRefreshing()) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
        );
        setListener();
        refreshLayout.autoRefresh();
    }

    private void setListener() {
//        listView.setMode(PullToRefreshBase.Mode.BOTH);
//        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
//            @Override
//            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
//                //设置下拉式显示的时间
//                String label = new Date().toLocaleString();
//                // 更新显示的label
//                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
//                getOrderList();
//            }
//        });

        refreshLayout.setEnableLoadmore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                String label = new Date().toLocaleString();
                // 更新显示的label
                totalPage = 0;
                page = 1;
                getOrderList();

                refreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                if(!refreshLayout.isEnableLoadmore()) refreshlayout.setEnableLoadmore(true);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                Log.e("page" + page, "totalPage" + totalPage);
                if (page <= totalPage) {
                    refreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                    getOrderList();
                } else {
                    refreshlayout.finishLoadmore();
                    refreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                }
            }
        });
        orderAdapter0.setOnButtonListener(new OrderAdapter0.ButtonOnclikListener() {
            @Override
            public void redButtonLitener(OrderObject orderObject, int position) {
                String typeStatus = orderObject.getStatusToString();
                switch (typeStatus) {
                    case "待收货":
                    case "卖家已发货":
                        String windowMsg = context.getString(R.string.isreceive_order);
                        cancleOrder(orderObject, windowMsg, "确认收货");
                        break;
                    case "待付款":
                        if(orderObject.getIs_global()==1){//1为全球购商品
                            toast(getString(R.string.not_support_global_goods));
                        }else {
                            PayActivity.jump((Activity) context, orderObject);
                        }
                        break;
                }
            }

            @Override
            public void graButtonLitener(OrderObject orderObject, int position) {
                String typeStatus = orderObject.getStatusToString();
                switch (typeStatus) {
                    case "待付款":
                        String windowMsg = context.getString(R.string.iscancle_order);
                        cancleOrder(orderObject, windowMsg, "取消订单");
                        break;
                    case "待发货":
                    case "买家已付款":
//                        toast("已提醒店家发货！");
                        confirmSendGoods();
                        break;
                    case "待收货":
                    case "卖家已发货":
                        //查看物流
                        LogisticsActivity.jump(getActivity(),orderObject.getPayment_id());
                        break;
                }
            }
        });

    }


    android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0://接口加载成功
                    orderAdapter0.notifyDataSetChanged();
                    break;
                case 1://接口加载失败

                    break;
            }
        }
    };

    //-------------------adapter处理-----------------------
    private ConfirmDialog.Builder cancleOrderDialog;
    private MessageDialog.Builder messageOrderDialog;

    /**
     * 取消订单dialog
     */
    private void cancleOrder(final OrderObject orderObject, String content, final String orderStatus) {
        if (cancleOrderDialog == null) {
            cancleOrderDialog = new ConfirmDialog.Builder(context);
        }
        cancleOrderDialog.setContent(content);
        cancleOrderDialog.setContentGravity(Gravity.CENTER_HORIZONTAL);
        cancleOrderDialog.setPositiveButton("确定", new ConfirmDialog.Builder.OnPositiveListener() {
            @Override
            public void onPositive(ConfirmDialog dialog) {
                dialog.dismiss();
                switch (orderStatus) {
                    case "取消订单":
                        cancleOrder(orderObject.getPayment_id());
                        break;
                    case "确认收货":
                        confirmOrder(orderObject.getPayment_id());
                        break;
                }
            }
        });
        cancleOrderDialog.show();
    }

    /**
     * 提醒发货
     */
    private void confirmSendGoods() {
        if (messageOrderDialog == null) {
            messageOrderDialog = new MessageDialog.Builder(context);
        }
        messageOrderDialog.setContent("已提醒店家发货！ ");
        messageOrderDialog.setContentGravity(Gravity.CENTER_HORIZONTAL);
        messageOrderDialog.setPositiveButton("确定", new MessageDialog.Builder.OnPositiveListener() {
            @Override
            public void onPositive(MessageDialog dialog) {
                dialog.dismiss();
            }
        });
        messageOrderDialog.show();
    }

    /**
     * 获取购物车列表
     */
    int page = 1;
    int pageSize = 10;
    int totalPage = 0;
    List<com.lishe.lishe.lishe.module.myorder.bean.OrderObject> orderObjects = new ArrayList<>();

    private void getOrderList() {
        OrderPresenter.getInstance().getOrderList(Globals.getToken(), ORDER_TYPE + "", page + "", pageSize + "", new DataResponseListener<BaseOrderDataBody>() {
            @Override
            public void onSuccess(BaseOrderDataBody dataResponse) {
                Log.e("长度",orderObjects.size()+"");
                if(page==1){
                    orderObjects.clear();
                    orderAdapter0.notifyDataSetChanged();
                }
                orderObjects.addAll(dataResponse.getOrders());
                page = page + 1;
                totalPage = dataResponse.getTotalPage();
                handler.sendEmptyMessage(0);
                refreshLayout.finishLoadmore(500,true);
                refreshLayout.finishRefresh(500,true);
                if (orderObjects.size() == 0) {
                    emptyLayout.setVisibility(View.VISIBLE);
                    tipText.setText("没有订单~");
                    refreshLayout.setEnableLoadmore(false);
                } else {
                    emptyLayout.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFail(String failMessage) {
                refreshLayout.finishLoadmore(2000,false);
                refreshLayout.finishRefresh(2000,false);
                if (orderObjects.size() == 0) {
                    emptyLayout.setVisibility(View.VISIBLE);
                    tipText.setText("加载失败~");

                    refreshLayout.setLoadmoreFinished(true);
                    refreshLayout.setEnableLoadmore(false);//不触发加载更多
                }
            }

            @Override
            public void onError(Throwable e) {
                if (orderObjects.size() == 0) {
                    emptyLayout.setVisibility(View.VISIBLE);
                    tipText.setText("网络或服务器异常~");

                    refreshLayout.setLoadmoreFinished(true);
                    refreshLayout.setEnableLoadmore(false);//不触发加载更多
                }
                refreshLayout.finishLoadmore(2000,false);
                refreshLayout.finishRefresh(2000,false);
            }
        });
    }

    /**
     * 取消订单
     *
     * @param paymentId
     */
    private void cancleOrder(String paymentId) {
        OrderPresenter.getInstance().cancelOrder(Globals.getToken(), paymentId, new DataResponseListener<BaseRequestBody>() {
            @Override
            public void onSuccess(BaseRequestBody dataResponse) {
                refreshLayout.autoRefresh();
                toast(dataResponse.getMsg());
            }

            @Override
            public void onFail(String failMessage) {
                toast(failMessage);
            }

            @Override
            public void onError(Throwable e) {
                toast("取消失败，服务器或网络异常！");
            }
        });
    }

    /**
     * 确认收货
     *
     * @param paymentId
     */
    private void confirmOrder(String paymentId) {
        OrderPresenter.getInstance().confirmOrder(Globals.getToken(), paymentId, new DataResponseListener<BaseRequestBody>() {
            @Override
            public void onSuccess(BaseRequestBody dataResponse) {
                refreshLayout.autoRefresh();
                toast(dataResponse.getMsg());
            }

            @Override
            public void onFail(String failMessage) {
                toast(failMessage);
            }

            @Override
            public void onError(Throwable e) {

            }
        });
    }
}
